package com.zhoug.common3.json.adapter;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * int序列化转化器
 *
 * @Author: zhoug
 * @Date: 2023/3/17
 * @Description:
 */
public class IntTypeAdapter extends TypeAdapter<Number> {

    @Override
    public void write(JsonWriter out, Number value) throws IOException {
        out.value(value);
    }

    @Override
    public Number read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return 0;
        }
        String result = in.nextString();
        if (result == null || result.trim().isEmpty()) {
            return 0;
        }
        result=result.trim();
        int re = 0;
        try {
            re = Integer.parseInt(result);
        } catch (Exception e) {
//            e.printStackTrace();
            try {
                Matcher matcher = Pattern.compile("[\\+\\-]?\\d+").matcher(result);
                if (matcher.find()) {
                    String group = matcher.group();
                    re = Integer.parseInt(group);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return re;
    }
}
